//
//  PEDeviceSetVC.m
//  RuiHeAppApp
//
//  Created by Yan Chen on 2023/12/8.
//

#import "RHDeviceParaSetVC.h"
#import "JXCategoryView.h"
#import "JXCategoryListContainerView.h"
#import "RHDeviceParaSetListVC.h"
#import "RHEndPointTypeModel.h"
#import "RHNavTitleView.h"
#import "SettingsViewController.h"

@interface RHDeviceParaSetVC ()<JXCategoryListContainerViewDelegate,JXCategoryViewDelegate,JXCategoryTitleViewDataSource>

@property (nonatomic, strong) NSArray *titles;

@property (nonatomic, strong) JXCategoryTitleView *categoryView;

@property (nonatomic, strong) JXCategoryListContainerView *listContainerView;

//端点类型数组
@property (nonatomic ,strong) NSMutableArray <RHEndPointTypeModel*>*typeArray;

@property (nonatomic, strong) LYEmptyView *emptyView;

@property (nonatomic, strong) RHNavTitleView *titleView;
@end

@implementation RHDeviceParaSetVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view setBackgroundColor:CFTabViewBgColor];
    
    [self setupUI];
    [self getDeviceStatus];
    [self getEndPointReration];
}



- (void)setupUI{
    self.titleView = [[RHNavTitleView alloc]init];
    [self.titleView hideArrowImg];
    self.titleView.devNameLab.text = self.deviceModel.deviceName;
    self.titleView.devIdLab.text = self.deviceModel.deviceId;
    self.titleView.status = self.deviceModel.status;
    self.navigationItem.titleView = self.titleView;
    
    
    _listContainerView = [[JXCategoryListContainerView alloc] initWithType:JXCategoryListContainerType_ScrollView delegate:self];
    [self.view addSubview:self.listContainerView];
    
    _categoryView = [[JXCategoryTitleView alloc] initWithFrame:CGRectMake(0,0, [UIScreen mainScreen].bounds.size.width, 50)];
    self.categoryView.titles = self.titles;
    self.categoryView.backgroundColor = [UIColor whiteColor];
    self.categoryView.delegate = self;
    self.categoryView.titleSelectedColor = CMainColorGreen;
    self.categoryView.titleColor = kCOLOR_HEX(@"969799");
    self.categoryView.titleFont = [UIFont systemFontOfSize:14];
    self.categoryView.titleSelectedFont = [UIFont boldSystemFontOfSize:14];
    self.categoryView.titleColorGradientEnabled = YES;
    self.categoryView.titleLabelZoomEnabled = NO;
    self.categoryView.titleLabelZoomScale = 1.0;
    self.categoryView.cellWidth = JXCategoryViewAutomaticDimension;//自动宽度
    self.categoryView.cellSpacing = 20;
//    self.categoryView.contentEdgeInsetLeft = 20;
//    self.categoryView.contentEdgeInsetRight = 20;
    self.categoryView.titleLabelVerticalOffset = -10;
    [self.view addSubview:self.categoryView];
    self.categoryView.listContainer = self.listContainerView;
    
    JXCategoryIndicatorBackgroundView *backgroundView = [[JXCategoryIndicatorBackgroundView alloc] init];
//     backgroundView.size = CGSizeMake(60, 3);//自动宽度
     backgroundView.indicatorColor = CMainColorGreen;
     backgroundView.indicatorHeight = 3;
//     backgroundView.indicatorWidth = 60;
     backgroundView.verticalMargin = -10;
     backgroundView.indicatorCornerRadius = 1.5;

     _categoryView.indicators = @[backgroundView];
    
    
    [_categoryView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_offset(0);
        make.top.mas_offset(0);
        make.height.mas_equalTo(50);
    }];
    
    [_listContainerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_offset(0);
        make.top.equalTo(self.categoryView.mas_bottom).offset(0);
        make.bottom.mas_offset(0);
    }];
    
    
}



#pragma mark ------ 更新设备在线状态
-(void)getDeviceStatus
{
//    [QMUITips showLoadingInView:self.view];
    NSString *url = [NSString stringWithFormat:@"%@%ld",H_getDeviceInfo,self.deviceModel.device_id];
    [BaseModel startGetWithCompletionAPIKey:url argument:@{} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if(resultModel.code == 200){
            self.titleView.status = request.responseJSONObject[@"data"][@"status"];
            
        }
        
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
            
    }];
}

#pragma mark ----- 更新模块在线状态 -------
//这里只对状态处理,不对整个结构进行重新加载,会比较慢,体验不好
-(void)getModueStatus
{
//    [QMUITips showLoadingInView:self.view];
    NSString *url = [NSString stringWithFormat:@"%@/%@",H_getEndpointTypeParamList,self.deviceModel.deviceId];
    [RHEndPointTypeModel startGetWithCompletionAPIKey:url argument:@{} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if(resultModel.code == 200){
            NSArray *typeArr = resultModel.data;
            RHDeviceParaSetListVC *setVC = self.listContainerView.validListDict[@(self.categoryView.selectedIndex)];
            if (setVC && (self.categoryView.selectedIndex < typeArr.count)) {
                [setVC updateEndpointTypeModel:typeArr[self.categoryView.selectedIndex]];
            }
           
        }else{
            [self.view addSubview:self.emptyView];
        }
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
    }];
}

#pragma mark -----1. 获取设备端点关系 -------
- (void)getEndPointReration{
    [QMUITips showLoadingInView:self.view];
    NSString *url = [NSString stringWithFormat:@"%@/%@",H_getEndpointTypeParamList,self.deviceModel.deviceId];
    [RHEndPointTypeModel startGetWithCompletionAPIKey:url argument:@{} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if(resultModel.code == 200){
        
            NSArray *typeArr = resultModel.data;
            
            NSMutableArray *mtbArr = [NSMutableArray array];
            [self.typeArray removeAllObjects];
            [typeArr enumerateObjectsUsingBlock:^(RHEndPointTypeModel  *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                [mtbArr addObject:obj.endpointTypeName];
            }];
            self.typeArray = typeArr.mutableCopy;
            self.titles = mtbArr.copy;
            self.categoryView.titles = self.titles;
            [self.categoryView reloadData];
            //如果有逆变器
            [self.typeArray enumerateObjectsUsingBlock:^(RHEndPointTypeModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                if ([obj.endpointTypeCode isEqualToString:@"InvVoltronicLv"]||
                    [obj.endpointTypeCode isEqualToString:@"InvMegarevoLv"]) {
                    [self getIverterType:obj];
                    *stop = YES;
                }
            }];
            
            if (typeArr.count == 0) {
                [self.view addSubview:self.emptyView];
            }
        }else{
            [self.view addSubview:self.emptyView];
        }
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
    }];
    
    
}

#pragma mark -------2. 获取逆变器类型 为日月元而设---------
-(void)getIverterType:(RHEndPointTypeModel*)endPointTypeModel
{
    if (endPointTypeModel.nodes.count==0) {
        return;
    }
    RHEndPointModel *endpointModel = [endPointTypeModel.nodes firstObject];
    
    NSDictionary *para = @{@"deviceId":self.deviceModel.deviceId,
                           @"endpointTypeCode":endpointModel.endpointCode,
                           @"keyCodes":@[@"Inv_DevType"],
                           @"endpointSn":endpointModel.sn
    };
    [BaseModel startWithCompletionAPIKey:D_getLastEndpointData argument:para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
       
        if(resultModel.code == 200){
            self.deviceModel.inverterType = (DevInverterType)[request.responseJSONObject[@"data"][@"Inv_DevType"] integerValue];
            [self.categoryView reloadData];
        }
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
       
    }];
}



#pragma mark - JXCategoryViewDelegate

// 点击选中或者滚动选中都会调用该方法。适用于只关心选中事件，不关心具体是点击还是滚动选中的。
- (void)categoryView:(JXCategoryBaseView *)categoryView didSelectedItemAtIndex:(NSInteger)index {
    NSLog(@"%@", NSStringFromSelector(_cmd));
    // 侧滑手势处理
    self.navigationController.interactivePopGestureRecognizer.enabled = (index == 0);
    
//    self.subTitleLab.text = index==0?self.deviceModel.deviceId:self.deviceModel.typeName;
    
//    RHDeviceParaSetListVC *setVC = self.listContainerView.validListDict[@(index)];
//    setVC.endPointTypeModel = self.typeArray[index];

}

// 滚动选中的情况才会调用该方法
- (void)categoryView:(JXCategoryBaseView *)categoryView didScrollSelectedItemAtIndex:(NSInteger)index {
    NSLog(@"%@", NSStringFromSelector(_cmd));
}

#pragma mark - JXCategoryListContainerViewDelegate
// 返回列表的数量
- (NSInteger)numberOfListsInlistContainerView:(JXCategoryListContainerView *)listContainerView {
    return  self.titles.count;
}

// 返回各个列表菜单下的实例，该实例需要遵守并实现 <JXCategoryListContentViewDelegate> 协议
- (id<JXCategoryListContentViewDelegate>)listContainerView:(JXCategoryListContainerView *)listContainerView initListForIndex:(NSInteger)index {
    RHEndPointTypeModel *typeModel = self.typeArray[index];
    kWeakSelf;
    RHDeviceParaSetListVC *setVC = [[RHDeviceParaSetListVC alloc]init];
    setVC.deviceModel = self.deviceModel;
    setVC.endPointTypeModel = typeModel;
    setVC.updateDevStatus = ^{
        [weakSelf getDeviceStatus];
        [weakSelf getModueStatus];
    };
    return setVC;
    
  
}

-(LYEmptyView *)emptyView
{
    if (!_emptyView) {
        _emptyView = [LYEmptyView emptyViewWithImageStr:@"nodata_icon_1" titleStr:@"没有数据".rh_localized detailStr:@""];
        _emptyView.frame = CGRectMake((kUI_WINDOW_W-100)/2, (kUI_WINDOW_H-100-kNavHeight)/2, 100, 100);
    }
    return _emptyView;
}

@end
